package com.zjw.remotecall.utils;

import android.app.Application;

import androidx.annotation.NonNull;


import com.zjw.remotecall.constant.RemoteConstant;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;


/**
 * @author ：zhong.jw
 * @date ：Created in 2022/11/7 8:49
 */
public final class RemoteUtils {

    private final static Random sRandom = new Random();

    private static String packageName = "";

    private static final Map<String,AtomicLong> sSync = new ConcurrentHashMap<>();


    public static long forLong() {
        return sRandom.nextLong();
    }


    @SuppressWarnings("all")
    public static String createDefaultDescriptor() {
        if (packageName == null || packageName.isEmpty()) {
            try {
                Class<?> activity = Class.forName("android.app.ActivityThread");
                Field thread = activity.getDeclaredField("sCurrentActivityThread");
                Application app = (Application) activity.getMethod("getApplication").invoke(thread);
                packageName = app.getPackageName();
            } catch (Exception ignore) {

            }
        }
        return RemoteConstant.DEFAULT_DESCRIPTOR + packageName + "r@" + RemoteUtils.forLong();
    }

    public static long sync(@NonNull String syncKey) {
        AtomicLong atomicLong = sSync.computeIfAbsent(syncKey, key -> new AtomicLong(0));
        return atomicLong.getAndIncrement();
    }
}
